<template>
  <div class="personal-main">
    <div class="personal-pay">
      <h3><i>面部识别录入上传中心</i></h3>
      <div class="user-borrower" style="margin-top: 60px;width: 300px;margin-left: 120px">

        <div id="contentHolder">
          <video id="video" width="320" height="320" autoplay></video>
          <input type="button" id="snap" style="width:100px;height:35px;" value="拍 照"/>
          <canvas style="margin-top: 30px" id="canvas" width="320" height="320"></canvas>
          <input type="button" style="width: 100px;height: 35px" value="录入" @click="registered"/>
        </div>

      </div>

    </div>
  </div>
</template>

<script>
import $ from "jquery";

export default {
  name: "face",
  mounted() {
    //这段代码主要是获取摄像头的视频流并显示在Video标签中
    window.addEventListener("DOMContentLoaded", function () {
      var canvas = document.getElementById("canvas"),
          context = canvas.getContext("2d"),
          video = document.getElementById("video"),
          videoObj = {"video": true},
          errBack = function (error) {
            console.log("Video capture error: ", error.code);
          };
      $("#snap").click(function () {
        context.drawImage(video, 0, 0, 330, 250);
      })
      //navigator.getUserMedia这个写法在Opera中好像是navigator.getUserMedianow
      if (navigator.getUserMedia) {
        navigator.getUserMedia(videoObj, function (stream) {
          video.srcObject = stream;
          video.play();
        }, errBack);
      } else if (navigator.webkitGetUserMedia) {
        navigator.webkitGetUserMedia(videoObj, function (stream) {
          video.src = window.webkitURL.createObjectURL(stream);
          video.play();
        }, errBack);
      }

    }, false);

  },

  methods: {
    // 录入
    registered() {
      var canvans = document.getElementById("canvas");
      // 获取浏览器页面的画布对象
      // 以下开始编 数据
      var imgData = canvans.toDataURL();
      // 将图像转换为base64数据
      var base64Data = imgData.substr(22);
      // 获取名称
      var name = JSON.parse(localStorage.getItem('userName'));
      console.log(name)
      //开始异步上
      this.$axios
          .post(`http://localhost:9090/loan/admin/registered`, this.$qs.stringify({ "img": base64Data, "name": name})).then(
          response => {
            console.log('请求成功了', response.data)

            if (response.data==='success'){
              alert("您的人脸信息身份录入成功！欢迎您，尊敬的：" + response.data);
              console.log(response.data)
            }else{
              alert("您的人脸信息身份录入失败！请重新录入");
            }

          },
          error => {
            console.log('error submit!!', error.message)
          }
      )


    },
  },
}
</script>

<style scoped>

</style>